package com.guojiang.guopicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guojiang.guopicturebackend.api.aliyunai.AliYunAiApi;
import com.guojiang.guopicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.guojiang.guopicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.guojiang.guopicturebackend.exception.BusinessException;
import com.guojiang.guopicturebackend.exception.ErrorCode;
import com.guojiang.guopicturebackend.exception.ThrowUtils;
import com.guojiang.guopicturebackend.manager.CosManager;
import com.guojiang.guopicturebackend.manager.upload.FilePictureUpload;
import com.guojiang.guopicturebackend.manager.upload.PictureUploadTemplate;
import com.guojiang.guopicturebackend.manager.upload.UrlPictureUpload;
import com.guojiang.guopicturebackend.mapper.PictureMapper;
import com.guojiang.guopicturebackend.model.dto.file.UploadPictureResult;
import com.guojiang.guopicturebackend.model.dto.picture.*;
import com.guojiang.guopicturebackend.model.entity.Picture;
import com.guojiang.guopicturebackend.model.entity.Space;
import com.guojiang.guopicturebackend.model.entity.User;
import com.guojiang.guopicturebackend.model.enums.PictureReviewStatusEnum;
import com.guojiang.guopicturebackend.model.enums.UserRoleEnum;
import com.guojiang.guopicturebackend.model.vo.picture.PictureVO;
import com.guojiang.guopicturebackend.model.vo.user.MaskedUserVO;
import com.guojiang.guopicturebackend.service.PictureService;
import com.guojiang.guopicturebackend.service.SpaceService;
import com.guojiang.guopicturebackend.service.UserService;
import com.guojiang.guopicturebackend.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static com.guojiang.guopicturebackend.utils.ColorTransformUtils.getTargetColorString;

/**
 * @author 过江辉
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-01-08 21:13:55
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private CosManager cosManager;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    /**
     * 上传/编辑图片（公共图库）
     *
     * @param inputSource          文件输入源
     * @param pictureUploadRequest
     * @param loginUser
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "请先登录");
        ThrowUtils.throwIf(inputSource == null, ErrorCode.PARAMS_ERROR, "图片为空");
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NO_AUTH_ERROR, "图片要上传的空间不存在，快去创建空间吧");
            // 已经改为使用统一的权限校验
//            // 如果空间存在，仅允许空间管理员上传
//            ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR, "无权上传图片到此空间");
            // 校验额度
            ThrowUtils.throwIf(space.getTotalCount() >= space.getMaxCount(), ErrorCode.OPERATION_ERROR, "云空间可上传图片数量已满");
            ThrowUtils.throwIf(space.getTotalSize() >= space.getMaxSize(), ErrorCode.OPERATION_ERROR, "云空间容量已满");
        }
        // 2. 判断是更新还是新增
        Long pictureId = null;
        if (pictureUploadRequest != null) {
            pictureId = pictureUploadRequest.getId();
        }
        // 如果是更新图片操作
        if (pictureId != null) {
            // 校验图片是否存在数据库，不存在则操作失败
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在，无法更新");
            // 已经改为使用统一的权限校验
//            // 仅本人或管理员可更新（编辑）图片
//            ThrowUtils.throwIf(!(userService.isAdmin(loginUser) || oldPicture.getUserId().equals(loginUser.getId()))
//                    , ErrorCode.NO_AUTH_ERROR, "无权编辑图片");
            // 开启事务，删除旧图片占有的空间额度
            Long finalSpaceId = spaceId;
            transactionTemplate.execute(status -> {
                // 更新需要先删除对象存储中的旧图片数据
                this.clearCosPictureFile(oldPicture);
                // 这里不需要删除数据库的数据，因为后面会根据是更新还是上传新数据覆盖之前的数据库数据
                // 再删除旧图片占有的空间额度
                if (finalSpaceId != null) {
                    boolean updateResult = spaceService.lambdaUpdate()
                            .eq(Space::getId, finalSpaceId)
                            .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                            .setSql("totalCount = totalCount - 1")
                            .update();
                    ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "空间额度更新失败");
                }
                return oldPicture;
            });
            // 校验前后上传空间是否一致
            // 没传spaceId，则复用原来的spaceId（这样也兼容了公共图库）
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                ThrowUtils.throwIf(ObjUtil.notEqual(spaceId, oldPicture.getSpaceId()), ErrorCode.PARAMS_ERROR, "空间Id前后不一致");
            }
        }
        // 3. 上传图片，得到图片信息
        // 先按照空间划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
            // spaceId为空，表示上传到公共图库
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            // spaceId不为空，上传图片到对应的空间目录
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        // 根据 inputSource 的类型区分上传方式
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadPathPrefix);
        // 4. 构造入库对象
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        picture.setOriginUrl(uploadPictureResult.getOriginUrl());
        // 补充空间Id
        picture.setSpaceId(spaceId);
        // 原图是否可直接查看
        picture.setOriginView(uploadPictureResult.getOriginView());
        String picName = uploadPictureResult.getPicName();
        // 如果图片上传请求体中传递了图片名称，则默认选择
        // 这样保证了批量上传图片，管理员定义图片名称的灵活性
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setPicColor(uploadPictureResult.getPicColor());
        picture.setUserId(loginUser.getId());
        // 如果批量创建图片设置了分类和标签，则补充
        if (StrUtil.isNotBlank(pictureUploadRequest.getCategory())) {
            picture.setCategory(pictureUploadRequest.getCategory());
        }
        if (CollUtil.isNotEmpty(pictureUploadRequest.getTags())) {
            picture.setTags(JSONUtil.toJsonStr(pictureUploadRequest.getTags()));
        }
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 5. 插入数据到数据库
        // 如果pictureId不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 补充id和编辑时间（有id才能知道已经存在数据，自动判别为更新操作）
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 开启事务，插入新数据或更新旧数据，并更新空间额度
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            // 通过 saveOrUpdate 根据是否有id 自动更新或者新增图片对象
            boolean uploadResult = this.saveOrUpdate(picture);
            // 插入失败了，不需要更新空间额度
            ThrowUtils.throwIf(!uploadResult, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean updateResult = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "空间额度更新失败");
            }
            return picture;
        });
        return Picture.objToVo(picture);
    }

    /**
     * 获取图片查询对象
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值  
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        // 从多字段（图片名、图片简介、图片分类、图片标签）中模糊匹配
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件  
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
                    .or()
                    .like("category", searchText)
                    .or()
                    .like("tags", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.like(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        if (StrUtil.isNotBlank(picFormat)) {
            queryWrapper.eq("picFormat", picFormat);
            // 同时校验小写格式
            String lowerCase = picFormat.toLowerCase();
            queryWrapper.eq("picFormat", lowerCase);
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        // 大于等于（ge）开始编辑时间
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "createTime", startEditTime);
        // 小于（lt）结束编辑时间
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "createTime", endEditTime);
        // JSON 数组查询  
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序  
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }


    /**
     * 获取图片封装类视图
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        PictureVO pictureVO = Picture.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            MaskedUserVO maskedUserVO = userService.getMaskedUserVO(user);
            pictureVO.setUser(maskedUserVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装类视图
     *
     * @param picturePage
     * @param request
     * @return 图片封装类视图分页列表
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表  
        List<PictureVO> pictureVOList = pictureList.stream().map(Picture::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息  
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息  
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getMaskedUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }


    /**
     * 图片合法性校验
     *
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR, "图片不存在");
        // 取值等待校验
        Long id = picture.getId();
        String url = picture.getUrl();
        String pictureName = picture.getName();
        String introduction = picture.getIntroduction();
        // 修改数据时，id不能为空
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "图片Id不能为空");
        // 如果有图片名，图片名不能过长
        if (StrUtil.isNotBlank(pictureName)) {
            ThrowUtils.throwIf(pictureName.length() > 18, ErrorCode.PARAMS_ERROR, "图片名至多 18 个字符，请适当缩短");
        }
        // 如果传递了url（url不为空），则校验
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "图片网址无效");
        }
        // 如果有图片introduction，简介不能超过80个字符
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 80, ErrorCode.PARAMS_ERROR, "图片简介至多 80 个字符，请适当缩短");
        }
    }

    /**
     * 图片审核
     *
     * @param pictureReviewRequest
     * @param loginUser
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        Long reviewPictureId = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        Picture reviewPicture = this.getById(reviewPictureId);
        // 私有空间图片无权审核，也不需要审核，直接省去后面的校验
        ThrowUtils.throwIf(reviewPicture.getSpaceId() != null, ErrorCode.NO_AUTH_ERROR, "私有空间图片无权审核");
        // 1. 校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR, "图片审核请求为空");
        ThrowUtils.throwIf(reviewPictureId == null || reviewStatusEnum == null, ErrorCode.PARAMS_ERROR, "审核图片请求体参数有误");
        // 审核操作中 不能把已经通过的图片设置为待审核
        ThrowUtils.throwIf(PictureReviewStatusEnum.REVIEWING.equals(reviewStatus), ErrorCode.PARAMS_ERROR, "已过审图片不能设置为待审核");
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "请先登录");
        // 2. 判断图片是否存在
        ThrowUtils.throwIf(reviewPicture == null, ErrorCode.NOT_FOUND_ERROR, "要审核的图片不存在");
        // 3. 审核状态是否重复
        ThrowUtils.throwIf(reviewPicture.getReviewStatus() == reviewStatus
                , ErrorCode.OPERATION_ERROR, "图片已经是该审核状态 请勿重复审核");
        // 4. 数据库操作
        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean updateReviewStatusResult = this.updateById(updatePicture);
        if (!updateReviewStatusResult) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "审核失败 系统错误");
        }
    }

    /**
     * 在上传、更新、编辑图片以后填充审核相关参数
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        // 如果是管理员
        if (userService.isAdmin(loginUser)) {
            // 自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理创建、编辑图片，默认状态都是待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /**
     * 批量抓取和创建图片（管理员使用）
     *
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return 批量抓取的图片数
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 1. 校验参数
        // 管理员才能使用
        ThrowUtils.throwIf(!UserRoleEnum.ADMIN.getValue().equals(loginUser.getUserRole()), ErrorCode.NO_AUTH_ERROR, "无权限");
        // 常规参数校验
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR, "pictureUploadByBatchRequest 为空");
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        if (ObjUtil.isEmpty(count)) {
            count = 10;
        } else {
            if (count > 30) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "最多抓取30条");
            }
        }
        // 2. 抓取内容
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("Jsoup获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "Jsoup获取页面失败，请稍候重试");
        }
        // 3. 解析内容
        // 获取外层元素
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isEmpty(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败，请稍候重试");
        }
        // 获取图片元素列表
        Elements imgElementList = div.select("img.mimg");
        // 上传成功的数量
        int uploadCount = 0;
        // 图片前缀
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        // 如果名称前缀为空，默认设置为搜索词
        if (StrUtil.isBlank(namePrefix)) {
            namePrefix = searchText;
        }
        // 分类标签字段
        List<String> tags = pictureUploadByBatchRequest.getTags();
        String category = pictureUploadByBatchRequest.getCategory();
        // 遍历元素，依次上传图片
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题  
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片  
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileUrl(fileUrl);
            pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            pictureUploadRequest.setCategory(category);
            pictureUploadRequest.setTags(tags);
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 清理对象存储图片文件
     *
     * @param picture
     * @return
     */
    @Async
    @Override
    public void clearCosPictureFile(Picture picture) {
        // 1. 判断图片是否被多条数据关联（如果有秒传业务，这是必须判断的逻辑）
        String pictureUrl = picture.getUrl();
        long count = this.lambdaQuery().eq(Picture::getUrl, pictureUrl).count();
        // 找不到图片直接报错，给出提示信息
        ThrowUtils.throwIf(count < 1, ErrorCode.PARAMS_ERROR, "要删除的图片不存在");
        // 不止一条数据用到了这张图片，无法清理，给出提示信息
        ThrowUtils.throwIf(count > 1, ErrorCode.OPERATION_ERROR, "该图片关联多条数据，无法直接删除，请整理后再删除");
        // 2. 执行删除
        // 先删除 webp 压缩图
        if (StrUtil.isNotBlank(pictureUrl)) {
            cosManager.deleteObject(pictureUrl);
        }
        // 再删缩略图
        String thumbnailUrl = picture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)) {
            cosManager.deleteObject(thumbnailUrl);
        }
        // 再删原图
        String pictureOriginUrl = picture.getOriginUrl();
        if (StrUtil.isNotBlank(pictureOriginUrl)) {
            cosManager.deleteObject(pictureOriginUrl);
        }
    }

    @Override
    public boolean deletePicture(long pictureId, User loginUser) {
        // 校验请求体是否正常
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR, "请求参数非法");
        // 校验要删除的数据是否存在
        Picture picture = this.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "要删除的图片不存在");
        // 校验权限，已经改为 Sa-Token 注解鉴权
        // this.checkPictureAuth(picture, loginUser);
        // 开启事务
        Long spaceId = picture.getSpaceId();
        transactionTemplate.execute(status -> {
            // 先删除对象存储图片
            this.clearCosPictureFile(picture);
            // 再操作数据库删除图片
            boolean deleteResult = this.removeById(pictureId);
            ThrowUtils.throwIf(!deleteResult, ErrorCode.OPERATION_ERROR, "删除失败，系统错误");
            if (spaceId != null) {
                boolean updateResult = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + picture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR, "空间额度更新失败");
            }
            return picture;
        });
        return true;
    }

    @Override
    public boolean editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        Long editPictureId = pictureEditRequest.getId();
        // 编辑请求体是否正常
        ThrowUtils.throwIf(editPictureId <= 0, ErrorCode.PARAMS_ERROR, "请求参数非法");
        // 未登录不能编辑
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "无权限，请先登录");
        // 判断要编辑的图片是否存在
        Picture editPicture = this.getById(editPictureId);
        ThrowUtils.throwIf(editPicture == null, ErrorCode.NOT_FOUND_ERROR, "要编辑的图片不存在");
        if (editPicture.getSpaceId() != null) {
            ThrowUtils.throwIf(!loginUser.getId().equals(editPicture.getUserId())
                    , ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        // 在此处将实体类和 DTO 进行转换  
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 如果是前端创建图片功能的情况下
        // 先是上传图片，再到利用后端编辑图片接口补充图片名、图片简介、图片分类、图片标签等字段
        // 因为图片编辑请求体里并未携带图片创建者Id，但实际图片在上传时已经存入数据库，已经有了userId
        // 再下面补充这个字段，为校验图片操作权限（checkPictureAuth）做准备
        Picture databasePicture = this.getById(picture.getId());
        picture.setUserId(databasePicture.getUserId());
        // 注意将 list 转为 string  
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间  
        picture.setEditTime(new Date());
        // 数据校验  
        this.validPicture(picture);
        // 校验权限，已经改为 Sa-Token 注解鉴权
        // this.checkPictureAuth(picture, loginUser);
        // 补充审核参数
        this.fillReviewParams(picture, loginUser);
        // 操作数据库  
        boolean editResult = this.updateById(picture);
        ThrowUtils.throwIf(!editResult, ErrorCode.OPERATION_ERROR, "编辑图片失败，系统错误");
        return true;
    }


    /**
     * 校验用户是否有修改空间图片的权限
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void checkPictureAuth(Picture picture, User loginUser) {
        Long spaceId = picture.getSpaceId();
        Long loginUserId = loginUser.getId();
        Long pictureUserId = picture.getUserId();
        if (spaceId == null) {
            // 表示图片是公共图库的图片，仅图片创建者和管理员可以操作
            ThrowUtils.throwIf(!(pictureUserId.equals(loginUserId) || userService.isAdmin(loginUser))
                    , ErrorCode.NO_AUTH_ERROR, "无权操作图片");
        } else {
            // 非公共空间的图片，仅仅空间管理员可以操作
            ThrowUtils.throwIf(!pictureUserId.equals(loginUserId)
                    , ErrorCode.NO_AUTH_ERROR, "无权操作图片");
        }
    }

    /**
     * 主色调搜索相似图片
     *
     * @param spaceId
     * @param picColor
     * @param loginUser
     * @return
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR, "参数非法");
        if (spaceId != null) {
            ThrowUtils.throwIf(spaceId <= 0, ErrorCode.PARAMS_ERROR, "参数非法");
        }
        // 2. 校验空间权限
        // 未登录不能请求他人空间数据
        ThrowUtils.throwIf(loginUser == null && spaceId != null, ErrorCode.NO_AUTH_ERROR, "无权限");
        // 校验权限，已经改为 Sa-Token 注解鉴权
//        // 当前登录用户不是请求空间数据的空间管理员，同样驳回
//        if (spaceId != null) {
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(!space.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无权限");
//        }
        // 3. 查询该空间下的所有图片（必须有主色调，没有主色调的图片直接过滤）
        // 判断是否是查询公共空间
        if (spaceId != null) {
            List<Picture> pictureList = this.lambdaQuery()
                    .eq(Picture::getSpaceId, spaceId)
                    // 过滤没有主色调的图片
                    .isNotNull(Picture::getPicColor)
                    .list();
            // 使用迭代器遍历集合，剔除picColor为空字符串的元素
            Iterator<Picture> iterator = pictureList.iterator();
            while (iterator.hasNext()) {
                Picture picture = iterator.next();
                if (StrUtil.isBlank(picture.getPicColor())) {
                    iterator.remove();
                }
            }
            // 该空间没有有主色调字段的图片，直接返回空图片列表
            if (CollUtil.isEmpty(pictureList)) {
                return new ArrayList<>();
            }
            // 如果有，则将颜色字符串转换为主色调
            Color targetColor = Color.decode(getTargetColorString(picColor));
            // 4. 计算相似度并排序
            List<Picture> sortedPictureList = pictureList.stream()
                    // 过滤掉颜色相似度小于 0.65 的图片
                    .filter(picture -> {
                        String hexColor = picture.getPicColor();
                        Color pictureColor = Color.decode(hexColor);
                        double similarity = ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                        return similarity >= 0.65;
                    })
                    // sorted 默认值从小到大排序
                    .sorted(Comparator.comparingDouble(picture -> {
                        String hexColor = picture.getPicColor();
                        Color pictureColor = Color.decode(hexColor);
                        // 计算，越大越相似
                        return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                    }))
                    // 取前18个
                    .limit(18)
                    .collect(Collectors.toList());
            // 5. 返回结果
            return sortedPictureList.stream()
                    .map(Picture::objToVo)
                    .collect(Collectors.toList());
        } else {
            // 公共图库查询相似度
            List<Picture> pictureList = this.lambdaQuery()
                    // 过滤没有主色调的图片
                    .isNull(Picture::getSpaceId)
                    .isNotNull(Picture::getPicColor)
                    .list();
            // 使用迭代器遍历集合，剔除picColor为空字符串的元素
            Iterator<Picture> iterator = pictureList.iterator();
            while (iterator.hasNext()) {
                Picture picture = iterator.next();
                if (StrUtil.isBlank(picture.getPicColor())) {
                    iterator.remove();
                }
            }
            // 该空间没有有主色调字段的图片，直接返回空图片列表
            if (CollUtil.isEmpty(pictureList)) {
                return new ArrayList<>();
            }
            // 如果有，则将颜色字符串转换为主色调
            Color targetColor = Color.decode(getTargetColorString(picColor));
            // 4. 计算相似度并排序
            List<Picture> sortedPictureList = pictureList.stream()
                    // 过滤掉颜色相似度小于 0.65 的图片
                    .filter(picture -> {
                        String hexColor = picture.getPicColor();
                        Color pictureColor = Color.decode(hexColor);
                        double similarity = ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                        return similarity >= 0.65;
                    })
                    // sorted 默认从小到大排序
                    .sorted(Comparator.comparingDouble(picture -> {
                        String hexColor = picture.getPicColor();
                        Color pictureColor = Color.decode(hexColor);
                        // 计算，越大越相似
                        return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                    }))
                    // 取前18个
                    .limit(18)
                    .collect(Collectors.toList());
            // 5. 返回结果
            return sortedPictureList.stream()
                    .map(Picture::objToVo)
                    .collect(Collectors.toList());
        }
    }

    /**
     * 主色调搜索相似图片
     *
     * @param spaceId
     * @param picColor
     * @param loginUser
     * @return
     */
    @Override
    public List<Picture> searchPictureForAdminByColor(Long spaceId, String picColor, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR, "参数非法");
        if (spaceId != null) {
            ThrowUtils.throwIf(spaceId <= 0, ErrorCode.PARAMS_ERROR, "参数非法");
        }
        // 2. 校验空间权限
        // 未登录不能请求他人空间数据
        ThrowUtils.throwIf(loginUser == null && spaceId != null, ErrorCode.NO_AUTH_ERROR, "无权限");
        // 校验权限，已经改为 Sa-Token 注解鉴权
//        // 当前登录用户不是请求空间数据的空间管理员，同样驳回
//        if (spaceId != null) {
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(!space.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无权限");
//        }
        // 3. 查询该空间下的所有图片（必须有主色调，没有主色调的图片直接过滤）
        // 判断是否是查询公共空间
        if (spaceId != null) {
            List<Picture> pictureList = this.lambdaQuery()
                    .eq(Picture::getSpaceId, spaceId)
                    // 过滤没有主色调的图片
                    .isNotNull(Picture::getPicColor)
                    .list();
            // 使用迭代器遍历集合，剔除picColor为空字符串的元素
            Iterator<Picture> iterator = pictureList.iterator();
            while (iterator.hasNext()) {
                Picture picture = iterator.next();
                if (StrUtil.isBlank(picture.getPicColor())) {
                    iterator.remove();
                }
            }
            // 该空间没有有主色调字段的图片，直接返回空图片列表
            if (CollUtil.isEmpty(pictureList)) {
                return new ArrayList<>();
            }
            // 如果有，则将颜色字符串转换为主色调
            Color targetColor = Color.decode(getTargetColorString(picColor));
            // 4. 计算相似度并排序
            List<Picture> sortedPictureList = pictureList.stream()
                    // 过滤掉颜色相似度小于 0.65 的图片
                    .filter(picture -> {
                        String hexColor = picture.getPicColor();
                        Color pictureColor = Color.decode(hexColor);
                        double similarity = ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                        return similarity >= 0.65;
                    })
                    // sorted 默认值从小到大排序
                    .sorted(Comparator.comparingDouble(picture -> {
                        String hexColor = picture.getPicColor();
                        Color pictureColor = Color.decode(hexColor);
                        // 计算，越大越相似
                        return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                    }))
                    // 取前18个
                    .limit(18)
                    .collect(Collectors.toList());
            // 5. 返回结果
            return sortedPictureList;
        } else {
            // 公共图库查询相似度
            List<Picture> pictureList = this.lambdaQuery()
                    // 过滤没有主色调的图片
                    .isNull(Picture::getSpaceId)
                    .isNotNull(Picture::getPicColor)
                    .list();
            // 使用迭代器遍历集合，剔除picColor为空字符串的元素
            Iterator<Picture> iterator = pictureList.iterator();
            while (iterator.hasNext()) {
                Picture picture = iterator.next();
                if (StrUtil.isBlank(picture.getPicColor())) {
                    iterator.remove();
                }
            }
            // 该空间没有有主色调字段的图片，直接返回空图片列表
            if (CollUtil.isEmpty(pictureList)) {
                return new ArrayList<>();
            }
            // 如果有，则将颜色字符串转换为主色调
            Color targetColor = Color.decode(getTargetColorString(picColor));
            // 4. 计算相似度并排序
            List<Picture> sortedPictureList = pictureList.stream()
                    // 过滤掉颜色相似度小于 0.65 的图片
                    .filter(picture -> {
                        String hexColor = picture.getPicColor();
                        Color pictureColor = Color.decode(hexColor);
                        double similarity = ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                        return similarity >= 0.65;
                    })
                    // sorted 默认从小到大排序
                    .sorted(Comparator.comparingDouble(picture -> {
                        String hexColor = picture.getPicColor();
                        Color pictureColor = Color.decode(hexColor);
                        // 计算，越大越相似
                        return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                    }))
                    // 取前18个
                    .limit(18)
                    .collect(Collectors.toList());
            // 5. 返回结果
            return sortedPictureList;
        }
    }

    /**
     * 批量编辑图片
     *
     * @param pictureEditByBatchRequest
     * @param loginUser
     */
    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        // 1. 校验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR, "参数无效");
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR, "请先登录");
        // 2. 校验空间权限
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR, "要操作的空间不存在");
            ThrowUtils.throwIf(!space.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "无权操作该空间");
            // 3. 查询指定图片（仅选择需要的字段）
            List<Picture> pictureList = this.lambdaQuery()
                    .select(Picture::getId, Picture::getSpaceId, Picture::getUserId)
                    .eq(Picture::getSpaceId, spaceId)
                    .in(Picture::getId, pictureIdList)
                    .list();
            if (CollUtil.isEmpty(pictureList)) {
                return;
            }
            // 4. 更新分类和标签
            pictureList.forEach(picture -> {
                if (StrUtil.isNotBlank(category)) {
                    picture.setCategory(category);
                }
                if (CollUtil.isNotEmpty(tags)) {
                    picture.setTags(JSONUtil.toJsonStr(tags));
                }
            });
            // 批量重命名
            String nameRule = pictureEditByBatchRequest.getNameRule();
            fillPictureWithNameRule(pictureList, nameRule);
            // 5. 更新数据库
            boolean updateBatchResult = this.updateBatchById(pictureList);
            ThrowUtils.throwIf(!updateBatchResult, ErrorCode.OPERATION_ERROR, "系统错误，请稍候重试");
        }
        // 3. 查询指定图片（仅选择需要的字段）
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId, Picture::getUserId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if (CollUtil.isEmpty(pictureList)) {
            return;
        }
        // 对公共空间的图片操作，要校验当前登录用户对每张图片的编辑权限
        for (Picture picture : pictureList) {
            ThrowUtils.throwIf(!picture.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR, "选中图片中，存在无权限操作的图片");
        }
        // 4. 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        // 5. 更新数据库
        boolean updateBatchResult = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!updateBatchResult, ErrorCode.OPERATION_ERROR, "系统错误，请稍候重试");
    }

    /**
     * 创建扩图任务
     *
     * @param createPictureOutPaintingTaskRequest
     * @param loginUser
     * @return
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 1. 校验参数，获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR, "要扩图的图片不存在"));
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0 || picture == null
                , ErrorCode.NOT_FOUND_ERROR, "要扩图的图片不存在");
        // 校验分辨率
        Integer picWidth = picture.getPicWidth();
        Integer picHeight = picture.getPicHeight();
        ThrowUtils.throwIf(picWidth < 512 || picWidth > 4096 || picHeight < 512 || picHeight > 4096
                , ErrorCode.NOT_FOUND_ERROR, "该图片分辨率不支持 AI 扩图，支持范围：[512像素，4096像素]");
        // 校验格式
        String picFormat = picture.getPicFormat();
        ThrowUtils.throwIf(!(picFormat.equals("JPG") || picFormat.equals("JPEG")
                        || picFormat.equals("PNG") || picFormat.equals("WEBP") || picFormat.equals("webp"))
                , ErrorCode.NOT_FOUND_ERROR, "该图片格式不支持 AI 扩图，支持格式：[JPG、JPEG、PNG、HEIF、WEBP]");
        // 2. 校验权限，已经改为 Sa-Token 注解鉴权
        // checkPictureAuth(picture, loginUser);
        // 3. 创建扩图任务
        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        createOutPaintingTaskRequest.setInput(input);
        createOutPaintingTaskRequest.setParameters(createPictureOutPaintingTaskRequest.getParameters());
        // 4. 发送请求
        return aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);
    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (StrUtil.isBlank(nameRule) || CollUtil.isEmpty(pictureList)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片命名规则解析异常，请稍候重试");
        }
    }

    /**
     * 去掉前端传来的颜色参数的前缀，只保留后六位数
     *
     * @param colorStr
     * @return
     */
    private String parseColorString(String colorStr) {
        // 去掉 # 前缀
        if (colorStr.startsWith("#")) {
            colorStr = colorStr.substring(1);
        }
        // 加上一个 0x
        return colorStr;
    }
}




